const models = require('../db/db');
const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const $sql = require('../db/sqlMap');

const conn = mysql.createConnection(models.mysql);
conn.connect();

// // 注册接口
router.post('/register', (req, res) => {
	const params = req.body;
	const sel_sql = $sql.user.select + " where username = '" + params.username + "'";
	const add_sql = $sql.user.register;
	console.log(sel_sql);
	
	conn.query(sel_sql, params.username, (error, results) => {
		if(error) {
			console.log(err);
		}
		if (results.length != 0 && params.username == results[0].username) {
			res.send("-1");   // -1 表示用户名已经存在
		} else {
			conn.query(add_sql, [params.username, params.password], (err, rst) => {
				if (err) {
					console.log(err);
				} else{
					console.log(rst);
					res.send("0"); // 0 表示用户创建成功
				}
			});
		}
	});
});

// 登录接口
router.post('/login', (req, res) => {
	const params = req.body;
	const sel_sql = $sql.user.login
	console.log(sel_sql);
	
	conn.query(sel_sql, [params.username,params.password], (error, results) => {
		if(error) {
			console.log(err);
		}
		if (results!=null) {
			res.send(results);
		} 
		
	});
});



module.exports = router;